package com.funny.code.database;

import com.funny.code.resource.PropertyUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisException;

import javax.annotation.PostConstruct;
import java.util.Properties;

/**
 * Jedis工具类
 * 这是一个连接redis的工具类
 *
 * @Date: 2017/7/13 下午10:28
 * @Author: ironc
 * @Version: 1.0
 */
public class JedisUtils {

    private static JedisPool jedisPool = null;

    /**
     * 属性文件加载对象
     */
    private static Properties properties = PropertyUtils.load("redis.properties");

    private static void init(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.valueOf(properties.getProperty("maxTotal")));
        config.setMaxIdle(Integer.valueOf(properties.getProperty("maxIdle")));
        config.setMaxWaitMillis(Long.valueOf(properties.getProperty("maxTotal")));
        config.setTestOnBorrow(Boolean.valueOf(properties.getProperty("testOnBorrow")));
        try {
            jedisPool = new JedisPool(config, properties.getProperty("host"), Integer.valueOf(properties.getProperty("port")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static {
        if (jedisPool == null) {
            init();
        }
    }

    /**
     * 获取Jedis实例
     * @return
     */
    public static Jedis getJedis(){
        Jedis redis = null;
        try {
            if (jedisPool != null) {
                redis = jedisPool.getResource();
                return redis;
            } else {
                return null;
            }
        } catch (JedisException e) {
            e.printStackTrace();
        }finally {
            returnResource(redis);
        }
        return redis;
    }


    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool !=null) {
            jedis.close();
        }
    }

}
